
function getId(length = 10) {
  // 使用Date.now()生成基础的随机数
  let result = Date.now().toString(36);
  // 生成额外的随机数，确保ID的唯一性
  let extra = (Math.random().toString(36) + '0'.repeat(length)).substr(2, length);
  // 拼接两部分结果
  return result + extra;
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === 'getImages') {
    const { subDirs } = request.params

    const images = {}
    for (let i = 0; i < subDirs.length; i++) {
      // 获取所有的 xpath 参数
      const xpathList = getXPath(subDirs[i].xpath)

      images[subDirs[i].dirname] = []

      for (let j = 0; j < xpathList.length; j++) {
        const xpath = xpathList[j];
        
        // 获取所有满足 xpath 的 dom 节点
        const containers = document.querySelectorAll(`${xpath}`);

        if (!containers.length) continue;

        // 获取所有节点下面的图片
        containers.forEach(container => {
          images[subDirs[i].dirname].push(...getImagesUrl(container))
        })
      }
    }

    sendResponse({
      images,
      webUrl: window.location.href
    })
  }
})

function getImagesUrl(root) {
  const imagesDOM = root.querySelectorAll('img')

  let images = []
  for (let i = 0; i < imagesDOM.length; i++) {
    const image = imagesDOM[i];
    if (image.className.includes('video-icon')) {
      const videoContainer = document.querySelector('#detail-main-video-content')
      if (videoContainer) {
        const video = videoContainer.querySelector('video')
        images.push({
          src: video.src,
          id: getId()
        })
      } else {
        i++
      }
    } else {
      let src = image.dataset.lazyloadSrc || image.src
      images.push({
        src: src,
        id: getId()
      })
    }
  }
  return images
}

function getXPath(xpath) {
  return xpath.split("\n")
}